import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Textarea } from '@/components/ui/Textarea';
import { useStore } from '@/lib/hooks/useStore';
import { v4 as uuidv4 } from 'uuid';

// 验证架构
const planSchema = z.object({
  title: z.string().min(1, '标题不能为空'),
  description: z.string().optional(),
  startDate: z.string().refine(val => !isNaN(Date.parse(val)), {
    message: '请输入有效的开始日期',
  }),
  endDate: z.string().optional(),
});

type PlanFormData = z.infer<typeof planSchema>;

interface PlanFormProps {
  onSuccess?: () => void;
  initialData?: {
    id: string;
    title: string;
    description?: string;
    startDate: Date;
    endDate?: Date;
  };
}

export function PlanForm({ onSuccess, initialData }: PlanFormProps) {
  const { currentUser, addPlan, updatePlan } = useStore();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<PlanFormData>({
    resolver: zodResolver(planSchema),
    defaultValues: initialData
      ? {
          title: initialData.title,
          description: initialData.description || '',
          startDate: initialData.startDate.toISOString().substring(0, 16),
          endDate: initialData.endDate
            ? initialData.endDate.toISOString().substring(0, 16)
            : '',
        }
      : {
          title: '',
          description: '',
          startDate: new Date().toISOString().substring(0, 16),
          endDate: '',
        },
  });

  const onSubmit = async (data: PlanFormData) => {
    if (!currentUser) return;
    
    setIsSubmitting(true);
    
    try {
      const planData = {
        id: initialData?.id || uuidv4(),
        title: data.title,
        description: data.description,
        startDate: new Date(data.startDate),
        endDate: data.endDate ? new Date(data.endDate) : undefined,
        isCompleted: false,
        userId: currentUser.id,
      };
      
      if (initialData) {
        updatePlan(initialData.id, planData);
      } else {
        addPlan(planData);
      }
      
      reset();
      onSuccess?.();
    } catch (error) {
      console.error('保存计划失败', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div>
        <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">
          计划标题 <span className="text-red-500">*</span>
        </label>
        <Input
          id="title"
          placeholder="输入您的计划标题"
          {...register('title')}
          error={!!errors.title}
        />
        {errors.title && (
          <p className="mt-1 text-sm text-red-500">{errors.title.message}</p>
        )}
      </div>

      <div>
        <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">
          描述
        </label>
        <Textarea
          id="description"
          placeholder="输入计划描述（可选）"
          {...register('description')}
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label htmlFor="startDate" className="block text-sm font-medium text-gray-700 mb-1">
            开始时间 <span className="text-red-500">*</span>
          </label>
          <Input
            id="startDate"
            type="datetime-local"
            {...register('startDate')}
            error={!!errors.startDate}
          />
          {errors.startDate && (
            <p className="mt-1 text-sm text-red-500">{errors.startDate.message}</p>
          )}
        </div>

        <div>
          <label htmlFor="endDate" className="block text-sm font-medium text-gray-700 mb-1">
            结束时间
          </label>
          <Input
            id="endDate"
            type="datetime-local"
            {...register('endDate')}
            error={!!errors.endDate}
          />
          {errors.endDate && (
            <p className="mt-1 text-sm text-red-500">{errors.endDate.message}</p>
          )}
        </div>
      </div>

      <div className="flex justify-end space-x-2 pt-2">
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            reset();
            onSuccess?.();
          }}
        >
          取消
        </Button>
        <Button type="submit" variant="primary" disabled={isSubmitting}>
          {isSubmitting ? '保存中...' : initialData ? '更新计划' : '创建计划'}
        </Button>
      </div>
    </form>
  );
} 